﻿<?php
include_once("ThePage.class.php");
$page = new ThePage();
$data = $_REQUEST;
//获取id（db,tb,id），返回数据为 json 格式
$g = Factory::getItemClass('game_logic_send');
$g->send_1001("sanshi",4);
$tmp = $g->revc();  
$data['card_id'] = json_decode($tmp[0][1],true);
//取表情
/* 		
$temp_face = Factory::getBaseClass('Cache');
$c =$temp_face->set('file','ht');
$face_data = unserialize($c->get('face',0));
*/
$face_data = array('[微笑]'=>'微笑','[大笑]'=>'大笑','[抿嘴一笑]'=>'抿嘴一笑');
$data['face_data'] = $face_data;
if(!empty($_POST[submit])){
	$obj_card = new card_post();
	$obj_card->data = $data;
	$obj_card->execute();
}
//action type
$action_type = array(
	'main_card_add'=>'加主贴'
	,'follow_card_add'=>'加跟帖'
	,'forward_card_add'=>'加转帖'
	//,'main_card_del'=>'删主贴'
	//,'follow_card_del'=>'删跟帖'
	//,'forward_card_del'=>'删转贴'
);

//获取主贴
$oDB = Factory::getDB('t_main_card_temp');
$where = '1';
$oDB->setOrderBy($taxis="DESC");
$card_arr_show = $oDB->getAll($where,'mc_time',20);
//print_r($card_arr_show);
foreach($card_arr_show as $key =>$value){

  $format = '<li>%s say: %s   %s <br /><a href=" %S ?action_type=follow_card_add&main_id=%s">评论</a>  <a href="send.php?action_type=forward_card_add&main_id=%s">转帖</a><br />';
  $card_html_show .= sprintf($format,$value['user_id'],$value['mc_contents'],date("Y-m-d H:i:s",$value['mc_time']),$_SERVER['PHP_SELF'],$value['mc_id'],$value['mc_id']);
  if($value['mc_type'] == 2 || $value['mc_type'] == 3){
		$main_card_info = $oDB->getOne($value['mc_mutuality_mc_id']);
		$format = '   原帖：<br />    %s say: %s   %s <br />';
		$card_html_show .= sprintf($format,$main_card_info['user_id'],$main_card_info['mc_contents'],date("Y-m-d H:i:s",$main_card_info['mc_time']));
  }
  $card_html_show .= '<br />';
}

$page->smarty->assign('head_title', '添加帖子');
$page->smarty->assign('form_action_url', $_SERVER['PHP_SELF']);
$page->smarty->assign('action_type', $action_type);
$page->smarty->assign('request', $_REQUEST);
$page->smarty->assign('card_arr_show', $card_arr_show);
$page->smarty->assign('card_html_show', $card_html_show);
$page->smarty->assign('face_data', $face_data);
$page->smarty->display('send.tpl');

/**
 * 发帖类
 * @author Eric pei <peichunbin@ihandy.cn>
 * @version 1.0 2010-4-23
 */

class card_post{

    /**
     * 发帖执行函数
     */
	function execute(){	 
	   switch (TRUE){
		   case $this->data['action_type'] === 'main_card_add':
			   $this->result = $this->main_card_post();
			   break;
		   case $this->data['action_type'] === 'follow_card_add':
			   $this->result = $this->follow_card_post();
			   break;
		   case $this->data['action_type'] === 'forward_card_add':
			   $this->result = $this->forward_card_post();
			   break;
		   default:
			   echo "sorry,have no action type!";
			   break;
		}
	}
	
	/**
     * 发主贴
	 *  return true or false
     */
	function main_card_post(){
	     //数据处理
		 $values = $this->data_common_handle();
		// print_r($values);
		 $oDB = Factory::getDB('t_main_card_temp');
		 //$oDB->debug->debug=true;
		 $oDB->insert_t_main_card_temp($values);
		 //$error_sql = end($oDB->getDebugMsg());
		 //echo $error_sql;
		 //$oDB->insert('t_main_card_temp',$values);
		 print_r('最后一句话：'.$this->data['short_content']);
		 //最后一句话操作
		 return true;
	}
	
	/**
     * 发跟贴
	 * return true or false
     */
	function follow_card_post(){
	     //数据处理
		 $values = $this->data_common_handle();		 
		 $oDB = Factory::getDB('t_main_card_temp');
		 $main_card_info = $oDB->getOne($this->data['main_id']);
		 $values['mc_mutuality_mc_id'] = $main_card_info['mc_id'];
		 $values['mc_to_uid'] = $main_card_info['user_id'];
		 $values['mc_mutuality_uid'] = $main_card_info['user_id'];		 
		 $oDB->insert_t_main_card_temp($values);
		 return true;
	}
	
	/**
     * 发转贴
	 * return true or false
     */
	function forward_card_post(){
	     //数据处理
		 $values = $this->data_common_handle();		 	 
		 $oDB = Factory::getDB('t_main_card_temp');
		 $main_card_info = $oDB->getOne($this->data['main_id']);
		 $values['mc_mutuality_mc_id'] = $main_card_info['mc_id'];
		 $values['mc_to_uid'] = $main_card_info['user_id'];
		 $values['mc_mutuality_uid'] = $main_card_info['user_id'];		 
		 $oDB->insert_t_main_card_temp($values);
		 return true;
	}
	
	
	/**
     * 共同的数据处理
	 * return 
     */
	function data_common_handle(){ 
	    //删除html代码
		$this->data['card_content'] = DeleteHtml($this->data['card_content']);
		//屏蔽关键词替换
		$this->data['card_content'] = cut_str($this->data['card_content'], 140, 0);
		//图片处理
		$this->data_picture_handle();
		//最后一句话处理
		$this->data_last_say_handle();
		//话题数据处理
		$this->data_topic_handle();
		//跟踪用户(@)
		$this->data_at_user_handle();
		//表情处理
		$this->data_face_handle();
		//链接处理
		if(!empty($this->data['link'])){
				$this->data['card_content'] .= '<a href = "'.$this->data['link'].'">'.short_url($this->data['link']).'</a>';
		}
		//图片与主贴内容集成处理
		if(!empty($_SESSION['photo_url']))
		{
			if(empty($this->data['card_content']))
			{
				$this->data['short_content'] = '分享图片';
			}

			$this->data['card_content'] .= '<br><span class="hidden"><a href="' . HOST_UPLOAD_PATH_DEMO . $_SESSION['photo_url'].'" target="_blank"><img src="'.HOST_UPLOAD_PATH_DEMO . $_SESSION['photo_url'].'.s.jpg" alt="" /></a></span>';
			unset($_SESSION['photo_url']);
		}
		
		
		 $values['mc_id'] = join('',$this->data['card_id']);
		 $values['mc_db'] = $this->data['card_id']["db"];
		 $values['mc_table'] = $this->data['card_id']["tb"];
		 $values['mc_contents'] = $this->data['card_content'];
		 $values['user_id'] = $this->data['user_id'];
		 $values['mc_type'] = $this->action_type[$this->data['action_type']];
		 $values['mc_mutuality_mc_id'] = '';
		 $values['mc_to_uid'] = 0;
		 $values['mc_mutuality_uid'] = $this->data['to_user'];
		 $values['mc_topics'] = '';
		 $values['mc_state'] = 0;
		 $values['mc_sub'] = 0;
		 $values['mc_sub_value'] = '';
		 $values['mc_medium_type'] = 0;
		 $values['mc_send_type'] = 0;
		 $values['mc_time'] = time();
		 
		 return $values;
	}
	
	/**
     * 话题数据处理
	 * return unkown
     */
	function data_topic_handle(){
	    //正则查找 #topic# 
	    //$subject = '#jkljkf# fdsa#fsaf#jkljkf#few';
		preg_match_all('/#([^#]+)#/', $this->data['card_content'], $topicArr, PREG_PATTERN_ORDER);
		if(count($topicArr[1]) >= 1){
			$oDB = Factory::getDB('t_topic');		    
			foreach($topicArr[1] as $key => $value){
			   $value = trim($value);
			   $topic_id = short_url($topic_id);
			   $where = "topic_id = '".$topic_id."'";
			   # 检查db 里是否已存在，没有则插入
			   $result = $oDB->getAll($where);
			   if(!$result){
					$values['topic_id'] = $topic_id;
					$values['topic_type'] = 0;
					$values['topic_time'] = time();
					$values['topic_state'] = 0;
					$values['user_id'] = $this->data['user_id'];
					$values['topic_contents'] = $value;
					$oDB->insert_t_topic($values);
			   }
			   //组好链接替换回去
			   $value_show = ' <a href="topic_id='.short_url($topic_id).'" target="_blank" >'.$topicArr[0][$key].'</a>';
			   $this->data['card_content'] = str_replace($topicArr[0][$key], $value_show,  $this->data['card_content']);  
			}
		}
	}
	
	/**
     * 用户跟踪（@user） 处理
	 * return unkown
     */
	function data_at_user_handle(){
	    //正则提取
		preg_match_all('/(@ |@)([^., @;]+)/', $this->data['card_content'], $userArr, PREG_PATTERN_ORDER);
		if(count($userArr[2])>=1){
			foreach($userArr[2] as $key=>$value){
			    $this->data['to_user'] .= $value . ',';
				$oDB = Factory::getDB('t_user');
				$where = "user_name = '".$value."'";
				$result = $oDB->getAll($where);
				//if(!$result){
				//组好链接替换回去
				   $value_show = ' <a href="user_id='.$result['user_id'].'" target="_blank" >'.$userArr[0][$key].'</a>';
				   $this->data['card_content'] = str_replace($userArr[0][$key], $value_show,  $this->data['card_content']); 
			   //}
			}
		}
	}
		
	/**
     * 图片处理 
	 * return unkown
     */
	function data_picture_handle(){
		//上传图片的单独处理
			$cp = "photo_"; // 图片cookie前缀（约定）
			//文件上传
			if($_FILES && $_FILES['picture']['name'][0])
			{
				$file_upload = Factory::getBaseClass('Upload');
				$file_upload->uploadFileFize = 5120 * 1024; //设置文件上传大小为5M
				$file_upload->allowFile = array('png','jpeg', 'jpg', 'gif');
				$file_upload->init('picture');
				$file_upload->isDir = true;
				$filename = $file_upload->exec_upload(UPLOAD_PATH,1,1); //上传

				$ImageMagick = Factory::getBaseClass('ImageMagick');
				$source_file = $filename[0];
				$dest_file = $filename[0] . '.s.jpg';
				$ImageMagick->setParam($source_file, $dest_file);
				//$ImageMagick->Resize(80, 80);
				$size = getimagesize($source_file);
				if($size[0] <=80 && $size[1] <=80)
				{
					$width = $size[0];
					$height = $size[1];
				}else{
					if($size[0]>$size[1])
					{
						$width = 80;
						$height = round(80 * $size[1]/$size[0]);
					}
					else
					{
						$height = 80;
						$width = round(80 * $size[0]/$size[1]);
					}
				}
				$ImageMagick->Resize($width, $height);
				$ImageMagick->Save();


				$tmp = explode('/',$filename[0]);
				$img_name = end($tmp);
				$img_path = prev($tmp);
				$_tmp['sk_image'] = $img_path . '/' . $img_name;
				//$_tmp['sk_s_image'] = $img_path . '/' . $img_name . '.s.jpg';

				$photo = $_tmp['sk_image'];
				$name = $cp.$_REQUEST['photoNo']; // cookie名。依据cookie前缀及表单变量photoNo来生成（约定）
				$exp = time()+60*2; // 有效时间（默认2分钟）
				setcookie($name, $photo, $exp, '/');
				$_COOKIE[$name] = $photo; // 冗余赋值，让cookie即时生效。（约定）

				//启用session
				$_SESSION['photo_url'] = $photo;
			}			
	}
	
	/**
     * 表情处理
	 * return unkown
     */
	function data_face_handle(){
	    $face_data = $this->data['face_data'];
		if(!empty($face_data))
		{
			$face_html = array();
			foreach($face_data as $k => $v)
			{
				$face_html[] = '<img title="face" src="'.HOST_UPLOAD_PATH.'face/'.$v.'" alt="'.$k.'">';				
			}
			$this->data['card_content'] = str_replace(array_keys($face_data), $face_html, $this->data['card_content']);
			$this->data['short_content'] = str_replace(array_keys($face_data), $face_html, $this->data['short_content']);
		}
	}
	
	/**
     * 主贴统计处理
	 * return unkown
     */
	function data_statistic_handle(){
	
	}
	
	function data_last_say_handle(){
	   $totalLen = 15;
	   switch (TRUE){
		   case $this->data['action_type'] === 'main_card_add' && !empty($this->data['card_content']):
			   $this->data['short_content'] = $this->short_content($this->data['card_content'],$totalLen,array_keys($this->data['face_data']));
			   break;
		   case !empty($this->data['picture']):
			   $this->data['short_content'] = '分享图片';
			   break;
		   case !empty($this->data['link']):
			   $this->data['short_content'] = '分享链接';
			   break;
		   default:
			   break;
		}
	}
	
	/**
	 * 最后一句话内容 处理
	 *
	 * @param unknown_type $str
	 * @return unknown
	 */
	function short_content($subject = '',$totalLen = 15,$tagArrInDB = array())
	{
		//表情正则规则
		$pattern1 = '/(\\[[^\\[\\]]+\\])/';
		$pattern2 = '/\\[[^\\[\\]]+\\]/';
		if(mb_strlen($subject,"utf-8")>$totalLen )
		{  
			if (preg_match($pattern1, $subject))
			{
				//有匹配处理
				$splitStrArr = preg_split($pattern2, $subject);  //以表情为匹配分割字串
				preg_match_all($pattern1, $subject, $result, PREG_PATTERN_ORDER); 
				$tagArrInStr = $result[0];//取出字串中的表情
				$splitCount = count($splitStrArr);
				for ($i = 0,$remanentLen =$totalLen ; $i < $splitCount; $i++) 
				{
					//检测字串中的匹配是否是系统定义中的表情,是，作为一个字符处理，否，作为字串处理
					$isTagInDB = (in_array($tagArrInStr[$i], $tagArrInDB)) ? true : false;
					$splitStrArr[$i] = $isTagInDB ? $splitStrArr[$i] : $splitStrArr[$i].$tagArrInStr[$i];
					$splitValueLen = mb_strlen($splitStrArr[$i],"utf-8");
					if($splitValueLen>$remanentLen)
					{
					   $returnStr .= mb_substr($splitStrArr[$i], 0, $remanentLen, 'utf-8');
					   $ellipsisPoints = '...';
					   break;
					}
					elseif($splitValueLen == $remanentLen)
					{
					   $returnStr .= $splitStrArr[$i];
					   $ellipsisPoints = $i<($splitCount-1) && !empty($splitStrArr[$i+1])?'...' : '';
					   break;
					}
					else
					{
					   if($isTagInDB)
					   {
						   $returnStr .= $splitStrArr[$i].$tagArrInStr[$i];
						   $remanentLen -=$splitValueLen;
						   $remanentLen -=1;
					   }
					   else
					   {
						   $returnStr .= $splitStrArr[$i];
						   $remanentLen -=$splitValueLen; 
					   }
					   if( $remanentLen <= 0) 
					   {
						   $ellipsisPoints = $i<($splitCount-1)?'...' : '';
						   break;
					   }
					}
				}
			} 
			else 
			{	    
				$returnStr =  mb_substr($subject, 0, $totalLen, 'utf-8'); //没有匹配直接截取
				$ellipsisPoints = '...';
			}
			return $returnStr.$ellipsisPoints;
		}
		else
		{
		  return $subject;   //小于长度直接返回
		}
	}
	
 	/**
	 * @type array
	 * @access public
	 */
 public $data=array();
 
  	/**
	 * @type unkown
	 * @access public
	 */
 public $result;
 
  	/**
	 * @type array
	 * @access public
	 */
 public $action_type=array(
					'main_card_add'=>1,
					'follow_card_add'=>2,
					'forward_card_add'=>3,
 
					);
}


?>
